//
//  LoadingHub.m
//  OnionHome
//
//  Created by fengjie on 2019/9/13.
//  Copyright © 2019 FengJie. All rights reserved.
//

#import "LoadingHub.h"
static MBProgressHUD *hud = nil;

@implementation LoadingHub

+ (LoadingHub *)shareHUD{
    static LoadingHub *HUD = nil;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        HUD = [[LoadingHub alloc] init];
    });
    return HUD;
}
- (void)showMessage:(NSString *)_message{
    MBProgressHUD * hubMessage = [MBProgressHUD showHUDAddedTo:[self topUIWindow] animated:YES];
    hubMessage.label.text= _message;
    hubMessage.label.numberOfLines = 2;
    hubMessage.mode = MBProgressHUDModeText;
    hubMessage.removeFromSuperViewOnHide = YES;
    [hubMessage hideAnimated:YES afterDelay:kHUDDuration];
}

- (void)showMessage:(NSString *)_message duration:(CGFloat)_duration{
    [self hideHUD];
    if (hud == nil) {
        
        hud = [[MBProgressHUD alloc] initWithView:[self topUIWindow]];
        [[self topUIWindow] addSubview:hud];
        hud.mode = MBProgressHUDModeText;
        
        hud.margin = 14.0;
        hud.bezelView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.9];
        hud.contentColor = [UIColor whiteColor];
        hud.label.text = _message;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [hud showAnimated:YES];
        });
        
    } else {
        hud.label.text = _message;
        dispatch_async(dispatch_get_main_queue(), ^{
            [hud showAnimated:YES];
        });
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [hud hideAnimated:NO];
        [hud removeFromSuperview];
        hud = nil;
    });
}

- (void)showMessageWithActivityIndicatorView:(NSString *)_message{
    if (hud == nil) {
        hud = [[MBProgressHUD alloc] initWithView:[self topUIWindow]];
        hud.bezelView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.9];
        hud.contentColor = [UIColor whiteColor];
        hud.label.text = _message;
        [[self topUIWindow] addSubview:hud];
    }
    hud.label.text = _message;
    hud.mode = MBProgressHUDModeIndeterminate;
    [hud showAnimated:YES];
}
- (void)hideHUD{
    if (hud && hud.superview) {
        [hud hideAnimated:NO];
        [hud removeFromSuperview];
        hud = nil;
    }
}

-(UIWindow *)topUIWindow{
    
    NSArray *windows = [[UIApplication sharedApplication] windows];
    return [windows firstObject];//lastObject
}



@end
